//
//  EFAMsgControlTVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/8/4.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAMsgControlTVC.h"
#import "EFAMsgCtrlRecTCell.h"
#import "EFAMsgCtrlSendTCell.h"
#import "ApiManager.h"
#import "EFAModel.h"
#import "GlobalHeader.h"
#import <RongIMLib/RongIMLib.h>
#import <UIScrollView+EmptyDataSet.h>
#import "EFADeviceInfoVC.h"
#import "EFAAlarmAddVC.h"
#import "EFAAlarmVC.h"
#import "AlarmDisposeVC.h"
#import "DeviceDetailInfo.h"

@interface EFAMsgControlTVC ()<DZNEmptyDataSetDelegate, DZNEmptyDataSetSource, EFAMsgCtrlRecTCellDelegate>
@property (strong, nonatomic) UIRefreshControl *uiRefreshControl;

@property (strong, nonatomic) EFAMsgIMModel *imModel;   //!< 数据模型
@property (strong, nonatomic) EFAMsgUnhandleModel *allUnhandleMsgModel; ///< 所有的未读消息模型
@property (strong, nonatomic) NSMutableArray *deSelUnhandleMsgMArray;   ///< 未选中的消息数组
@end

static NSString *const kReuseRecvCellId = @"EFAMsgCtrlRecTCell";
static NSString *const kReuseSendCellId = @"EFAMsgCtrlSendTCell";
static NSInteger const kRequestMsgSize = 20;

@implementation EFAMsgControlTVC
#pragma mark - life cycle
- (void)dealloc {
        //当对象被回收时关闭通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:EFAGlobalNotiGETUIDispatchMsg object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNavigationBar];
    [self initSubViews];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rcimRefreshHandle:) name:EFAGlobalNotiGETUIDispatchMsg object:nil];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    // 刷新一下未处理故障
    [self requestDevUnhandleMsgList];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = self.device_name;
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"msg_filter"] style:UIBarButtonItemStylePlain target:self action:@selector(moreBarBtnTapped:)];
}

- (void)initSubViews {
    UINib *recvNib = [UINib nibWithNibName:kReuseRecvCellId bundle:nil];
    [self.tableView registerNib:recvNib forCellReuseIdentifier:kReuseRecvCellId];
    UINib *sendNib = [UINib nibWithNibName:kReuseSendCellId bundle:nil];
    [self.tableView registerNib:sendNib forCellReuseIdentifier:kReuseSendCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 60.0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    
    self.refreshControl = self.uiRefreshControl;
    
    // 融云的未读消息全部置为已读
//    NSString *targetId = [NSString stringWithFormat:@"device_%ld", (long)self.device_id];
//    [[RCIMClient sharedRCIMClient] clearMessagesUnreadStatus:ConversationType_PRIVATE targetId:targetId];
    // 请求数据
    [self.refreshControl beginRefreshing];
    [self requestDeviceMsgList];
    [self requestDevUnhandleMsgList];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"没有消息记录" attributes:dic];
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"global_empty"];
}
//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.imModel.device_msglist.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger count = self.imModel.device_msglist.count;
    if (indexPath.row < count) {
        EFAMsgIMItem *item = self.imModel.device_msglist[count - 1 - indexPath.row];
        if ([item.efairydevicemsg_from_id hasPrefix:@"user_"]) {
            EFAMsgCtrlSendTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseSendCellId forIndexPath:indexPath];
            [cell configViewWithIMItem:item];
              return cell;
        } else {
            EFAMsgCtrlRecTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseRecvCellId forIndexPath:indexPath];
            cell.nameLabel.text = self.device_name;
//            NSLog(@"tableViews的信息====》%@",item.efairymsg_content);
            [cell configViewWithIMItem:item];
            cell.delegate = self;
            return cell;
        }
    } else {
        EFAMsgCtrlSendTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseSendCellId forIndexPath:indexPath];
        return cell;
    }
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger count = self.imModel.device_msglist.count;
    if (indexPath.row < count) {
        EFAMsgIMItem *item = self.imModel.device_msglist[count - 1 - indexPath.row];
        if (item.efairydevicemsg_msgtype && !item.efairydevicemsg_ishandle) {
            return YES;
        }
    }
    return NO;
}
#pragma mark - UITableViewDelegate
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    return 0.1;
//}
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//    return 5.9;
//}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger count = self.imModel.device_msglist.count;
    if (indexPath.row < count) {
        EFAMsgIMItem *item = self.imModel.device_msglist[count - 1 - indexPath.row];
        BOOL isInAll = [self.allUnhandleMsgModel.unhandlemsg_list containsObject:@(item.efairydevicemsg_id)];
        BOOL isInDeselect = [self.deSelUnhandleMsgMArray containsObject:@(item.efairydevicemsg_id)];
        if (item.efairydevicemsg_msgtype && !item.efairydevicemsg_ishandle && isInAll && !isInDeselect) {
            [tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
        }
    }
}
//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
//}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"选中：%@", indexPath);
    if (tableView.isEditing) {
        NSInteger count = self.imModel.device_msglist.count;
        if (indexPath.row < count) {
            EFAMsgIMItem *item = self.imModel.device_msglist[count - 1 - indexPath.row];
            if (!(item.efairydevicemsg_msgtype && !item.efairydevicemsg_ishandle)) {
//                item.isSelected = NO;
                [self.deSelUnhandleMsgMArray addObject:@(item.efairydevicemsg_id)];
                [tableView deselectRowAtIndexPath:indexPath animated:YES];
            } else {
//                item.isSelected = YES;
                [self.deSelUnhandleMsgMArray removeObject:@(item.efairydevicemsg_id)];
            }
        }
    }
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"取消选中：%@", indexPath);
    NSInteger count = self.imModel.device_msglist.count;
    if (indexPath.row < count) {
        EFAMsgIMItem *item = self.imModel.device_msglist[count - 1 - indexPath.row];
//        item.isSelected = NO;
        [self.deSelUnhandleMsgMArray addObject:@(item.efairydevicemsg_id)];
    }
}

#pragma mark - EFAMsgCtrlRecTCellDelegate
- (void)msgCtrlRecvTCell:(EFAMsgCtrlRecTCell *)cell portraitTapped:(UIGestureRecognizer *)gesture {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSInteger count = self.imModel.device_msglist.count;
    EFAMsgIMItem *item = self.imModel.device_msglist[count - 1 - indexPath.row];
    NSRange range = [item.efairydevicemsg_from_id rangeOfString:@"device_"];
    if (range.length > 0) {
        if (self.isFromDeviceInfo) {
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
        
        
        DeviceDetailInfo *vc = [[DeviceDetailInfo alloc]init];
        vc.deviceId = [[item.efairydevicemsg_from_id substringFromIndex:range.length] integerValue];
        vc.device_name  = item.efairydevice_name;
//        EFADeviceInfoVC *vc = [[EFADeviceInfoVC alloc] init];
//        vc.deviceId = [[item.efairydevicemsg_from_id substringFromIndex:range.length] integerValue];
//        vc.device_name = item.efairydevice_name;
//        vc.isFromControl = YES;
        [self showViewController:vc sender:nil];
    }
}
- (void)msgCtrlRecvTCell:(EFAMsgCtrlRecTCell *)cell alarmBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSInteger count = self.imModel.device_msglist.count;
    NSInteger arrayIndex = count - 1 - indexPath.row;
    if (arrayIndex >= self.imModel.device_msglist.count || arrayIndex < 0) {
        return;
    }
    EFAMsgIMItem *item = self.imModel.device_msglist[arrayIndex];
    if (item.efairydevicemsg_msgtype && !item.efairydevicemsg_ishandle) {
        if ([self.delegate respondsToSelector:@selector(msgControlTVC:alarmBtnTapped:)]) {
            [self.delegate msgControlTVC:self alarmBtnTapped:btn];
        }
        // 进入编辑模式
        [self enterEditingMode:YES];
    } else {
        [self jumpToAlarmRcdDetailWithMsgId:item.efairydevicemsg_id];
    }
}
#pragma mark - event response
- (void)sendMsg:(EFAMsgIMItem *)msg {
    if (!msg) {
        return;
    }
    
    [self.imModel insertMsgItem:msg];
    if (self.imModel.device_msglist.count) {
//        // 刷新界面(之前老的刷新动画，升级到iOS11后发现抖动的厉害，下面是在网上搜的刷新效果，还不错)
//        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(self.imModel.device_msglist.count - 1) inSection:0];
//        [self.tableView beginUpdates];
//        [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
//        [self.tableView endUpdates];
//        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
        //解决刷新tableView  reloadData时闪屏的bug
        if(@available(iOS 11.0, *)) {   // 在iOS11.0上可以，但是iOS9.0又不行了，改为下面的动画
            self.tableView.hidden = YES;
            [self.tableView reloadData];
            if (self.imModel.device_msglist.count > 1) {
                // 动画之前先滚动到倒数第二个消息
                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.imModel.device_msglist.count - 2 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
            }
            self.tableView.hidden = NO;
            // 添加向上顶出最后一个消息的动画
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.imModel.device_msglist.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        } else {    // 在xcode9编译之后，发现iOS9.0动画又开始抖动了，现在这是测试出来还可以的效果
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(self.imModel.device_msglist.count - 1) inSection:0];
            self.tableView.hidden = YES;
            [self.tableView reloadData];
            if (self.imModel.device_msglist.count > 1) {
                // 动画之前先滚动到倒数第二个消息
                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.imModel.device_msglist.count - 2 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
            }
            self.tableView.hidden = NO;
            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
    };
}
- (void)refreshViewWithAlarmId:(NSInteger)alarm_id {
    if (self.alarm_id == alarm_id) {
        return;
    }
    
    self.alarm_id = alarm_id;
    [self.imModel removeAll];
    [self.allUnhandleMsgModel removeAll];
    [self requestDeviceMsgList];
    [self requestDevUnhandleMsgList];
}
- (void)enterEditingMode:(BOOL)editing {
    if (!editing) {
//        [self.imModel clearAllSelected];
        [self.deSelUnhandleMsgMArray removeAllObjects];
    }
    if (self.tableView.isEditing != editing) {
        [self.tableView setEditing:editing animated:!editing];
    }
    if (editing) {
        [self.tableView reloadData];
    }
}
- (void)wholeSelOrNot:(BOOL)wholeSel {
    [self.deSelUnhandleMsgMArray removeAllObjects];
    if (!wholeSel) {
        [self.deSelUnhandleMsgMArray addObjectsFromArray:self.allUnhandleMsgModel.unhandlemsg_list];
    }
    
    // 刷新界面
    [self.tableView reloadData];
}
- (void)completeSelection {
//    NSArray *selArray = self.imModel.selectedMsgIMArray;
//    NSArray *selIdArray = self.imModel.selectedMsgIMIdArray;
    NSMutableArray *temp = [self.allUnhandleMsgModel.unhandlemsg_list mutableCopy];
    [temp removeObjectsInArray:self.deSelUnhandleMsgMArray];
    [self enterEditingMode:NO];
    if (!temp.count) {
        return;
    }
    
//    EFAAlarmAddVC *vc = [[EFAAlarmAddVC alloc] init];
//    vc.device_id = self.device_id;
//    vc.msgIdArray = temp;
//    vc.successHandle = ^{
////        [self.imModel changeToHandleWithArray:temp];
//        [self.allUnhandleMsgModel.unhandlemsg_list removeObjectsInArray:temp];
//        [self refreshPromptView];
//        [self.imModel changeToHandleWithIdArray:temp];
//        [self.tableView reloadData];
//    };
//
    //确定跳转至报警处理页面
    AlarmDisposeVC *vc = [[AlarmDisposeVC alloc] init];
    vc.device_id = self.device_id;
    vc.msgIdArray = temp;
    vc.datasCourceVC = 0;
    vc.successHandle = ^{
        //        [self.imModel changeToHandleWithArray:temp];
        [self.allUnhandleMsgModel.unhandlemsg_list removeObjectsInArray:temp];
        [self refreshPromptView];
        [self.imModel changeToHandleWithIdArray:temp];
        [self.tableView reloadData];
    };
    [self showViewController:vc sender:nil];
}




- (void)rcimRefreshHandle:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        EFAMsgIMItem *msgItem = notification.object;
        if([msgItem.efairydevice_id intValue] == _device_id){
//            NSLog(@"推送古来的设备id:%@和内容====》: %@",msgItem.efairydevice_id,msgItem.efairymsg_content);
//            NSMutableArray<EFAMsgIMItem *> *mNSMArray = [[NSMutableArray alloc]init];
//            [mNSMArray addObject:msgItem];
//            if (!mNSMArray.count) {
//                return;
//            }
            // 新增数据
            [self.imModel insertMsgItem:msgItem];
            //解决刷新tableView  reloadData时闪屏的bug
            if(@available(iOS 11.0, *)) {
                self.tableView.hidden = YES;
                [self.tableView reloadData];
                if (self.imModel.device_msglist.count > 1){
                    // 动画之前先滚动到倒数第二个消息
                    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.imModel.device_msglist.count - 2 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                }
                self.tableView.hidden = NO;
                // 添加向上顶出最后一个消息的动画
                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.imModel.device_msglist.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
            } else {
                self.tableView.hidden = YES;
                [self.tableView reloadData];
                if (self.imModel.device_msglist.count > 1){
                    // 动画之前先滚动到倒数第二个消息
                    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.imModel.device_msglist.count - 2 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                }
                self.tableView.hidden = NO;
                // 添加向上顶出最后一个消息的动画
                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.imModel.device_msglist.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            }
        }else{
            return;
        }

        
        
        
        
        
//        EFAMsgIMItem *temp = [EFAMsgIMItem yy_modelWithJSON:notification.userInfo[@"extra"]];
//        // 这里要判断是不是该device的数据(后来发现，加入开机有很多推送，但是这里只报告了最后一条推送，有可能中间的才是该device的推送，所以这里不判断了)
//        NSString *targetId = [NSString stringWithFormat:@"device_%ld", self.device_id];
//        if (![temp.efairydevicemsg_from_id isEqualToString:targetId]) {
//            return ;
//        }
//        // 如果是，显示界面数据
//        [self.imModel insertMsgItem:temp];
//        // 刷新界面
//        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.imModel.device_msglist.count - 1 inSection:0];
//        [self.tableView beginUpdates];
//        [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
//        [self.tableView endUpdates];
//        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
//        // 清楚小红点(最后逻辑上会修改，不这样处理，参考笔记本)
//        // 融云的未读消息全部置为已读
//        [[RCIMClient sharedRCIMClient] clearMessagesUnreadStatus:ConversationType_PRIVATE targetId:targetId];
        
        // 只要有消息，直接从融云拉取该设备的未读消息
//        NSString *targetId = [NSString stringWithFormat:@"device_%ld", (long)self.device_id];
//        int unreadCnt = [[RCIMClient sharedRCIMClient] getUnreadCount:ConversationType_PRIVATE targetId:targetId];
//        if (!unreadCnt) {
//            NSLog(@"没有该设备的未读消息");
//            return;
//        }
//        // 对未读消息和已有的消息进行查重
//        NSArray<RCMessage *> *unreadMsgArray = [[RCIMClient sharedRCIMClient] getLatestMessages:ConversationType_PRIVATE targetId:targetId count:unreadCnt];
//        if (!unreadMsgArray.count) {
//            return;
//        }
//        // 立刻清空融云未读消息
//        long long time = [[RCIMClient sharedRCIMClient] getMessageSendTime:unreadMsgArray.firstObject.messageId];
//        [[RCIMClient sharedRCIMClient] clearMessagesUnreadStatus:ConversationType_PRIVATE targetId:targetId time:time];
//        // 对读取的消息进行处理
//        NSMutableArray<EFAMsgIMItem *> *mArray = [NSMutableArray arrayWithCapacity:unreadMsgArray.count];
//        for (RCMessage *message in unreadMsgArray) {
//            if ([message.content isMemberOfClass:[RCTextMessage class]]) {
//                RCTextMessage *testMessage = (RCTextMessage *)message.content;
//                if (testMessage.extra) {
//                    EFAMsgIMItem *temp = [EFAMsgIMItem yy_modelWithJSON:testMessage.extra];
//                    if (![self.imModel containsMsgWithMsgId:temp.efairydevicemsg_id]) {
//                        [mArray addObject:temp];
//                    }
//                }
//            }
//        }
//        if (!mArray.count) {
//            return;
//        }
//        // 新增数据
//        [self.imModel insertMsgItemArray:mArray];
//        // 刷新界面(之前老的刷新动画，升级到iOS11后发现抖动的厉害，下面是在网上搜的刷新效果，还不错)
//        NSMutableArray<NSIndexPath *> *indexPathArray = [NSMutableArray arrayWithCapacity:mArray.count];
//        NSInteger starIndex = self.imModel.device_msglist.count - mArray.count;
//        for (NSInteger i = 0; i < mArray.count; i++) {
//            [indexPathArray addObject:[NSIndexPath indexPathForRow:(starIndex + i) inSection:0]];
//        }
//        [self.tableView beginUpdates];
//        [self.tableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationFade];
//        [self.tableView endUpdates];
//        [self.tableView scrollToRowAtIndexPath:indexPathArray.lastObject atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
        
     
    });
}

#pragma mark - private methods
- (void)jumpToAlarmRcdDetailWithMsgId:(NSInteger)msgId {
    EFAAlarmVC *vc = [[EFAAlarmVC alloc] init];
    vc.msg_id = msgId;
    [self showViewController:vc sender:nil];
}
- (void)refreshPromptView {
    if ([self.delegate respondsToSelector:@selector(msgControlTVC:alarmCount:)]) {
        [self.delegate msgControlTVC:self alarmCount:self.allUnhandleMsgModel.unhandlemsg_list.count];
    }
}

- (void)tableViewEndRefresh {
    if ([self.refreshControl isRefreshing]) {
        [self.refreshControl endRefreshing];
    }
    if (self.imModel.totalLoad) {
        self.refreshControl = nil;
    } else {
        self.refreshControl = self.uiRefreshControl;
    }
}

- (EFAMsgIMModel *)msgListWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
    if ([dic[EFAGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.imModel;
    }
    
    EFAMsgIMModel *temp = [EFAMsgIMModel yy_modelWithDictionary:dic[EFAGlobalJsonKeyResult]];
    if (!temp) {
        return self.imModel;
    }
    
    if (AddMore && self.imModel) {
        [self.imModel addMoreWithData:temp];
    } else {
        self.imModel = temp;
    }
    return self.imModel;
}

#pragma mark - network request
- (void)requestDeviceMsgList {
    if (![EFAModel sharedInstance].isLogin) {
        [self tableViewEndRefresh];
        return;
    }
    
    NSInteger last_id = self.imModel.device_msglist.lastObject.efairydevicemsg_id;
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) forKey:@"efairyuser_id"];
    [pars setObject:[EFAModel sharedInstance].loginInfo.access_token forKey:@"access_token"];
    [pars setObject:@(self.device_id) forKey:@"efairydevice_id"];
    [pars setObject:@(last_id) forKey:@"last_id"];
    [pars setObject:@(kRequestMsgSize) forKey:@"size"];
    if (self.alarm_id != -1) {
        [pars setObject:@(self.alarm_id) forKey:@"alarm_id"];
    }
//    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
//                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
//                           @"efairydevice_id" : @(self.device_id),
//                           @"last_id" : @(last_id),
//                           @"size" : @(kRequestMsgSize)};
    NSLog(@"请求聊天记录的参数：%@", pars);
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiDeviceMsgList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求聊天记录返回：%@", responseObject);
        EFAMsgIMModel *temp = [EFAMsgIMModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        [self.imModel addMoreWithData:temp];
        [self.tableView reloadData];
        if (temp && temp.device_msglist.count) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:temp.device_msglist.count - 1 inSection:0];
            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
        }
        [self tableViewEndRefresh];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求聊天记录失败：%@", error);
        [self tableViewEndRefresh];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.navigationController.view message:msg];
    }];
}
- (void)requestDevUnhandleMsgList {
    if (![EFAModel sharedInstance].isLogin) {
        [self tableViewEndRefresh];
        return;
    }
    
//    NSInteger last_id = self.imModel.device_msglist.lastObject.efairydevicemsg_id;
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) forKey:@"efairyuser_id"];
    [pars setObject:[EFAModel sharedInstance].loginInfo.access_token forKey:@"access_token"];
    [pars setObject:@(self.device_id) forKey:@"efairydevice_id"];
//    [pars setObject:@(last_id) forKey:@"last_id"];
//    [pars setObject:@(kRequestMsgSize) forKey:@"size"];
    if (self.alarm_id != -1) {
        [pars setObject:@(self.alarm_id) forKey:@"alarm_id"];
    }

    NSLog(@"请求未读消息列表的参数：%@", pars);
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiDevUnhandleMsgList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求未读消息列表返回：%@", responseObject);
        self.allUnhandleMsgModel = [EFAMsgUnhandleModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        [self refreshPromptView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求未读消息列表失败：%@", error);
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.navigationController.view message:msg];
    }];
}
#pragma mark - getters and setters
- (EFAMsgIMModel *)imModel {
    if (!_imModel) {
        _imModel = [[EFAMsgIMModel alloc] init];
    }
    return _imModel;
}

- (UIRefreshControl *)uiRefreshControl {
    if (!_uiRefreshControl) {
        _uiRefreshControl = [[UIRefreshControl alloc] init];
        [_uiRefreshControl addTarget:self action:@selector(requestDeviceMsgList) forControlEvents:UIControlEventValueChanged];
    }
    return _uiRefreshControl;
}
- (NSMutableArray *)deSelUnhandleMsgMArray {
    if (!_deSelUnhandleMsgMArray) {
        _deSelUnhandleMsgMArray = [NSMutableArray array];
    }
    return _deSelUnhandleMsgMArray;
}
//- (void)setAlarm_id:(NSInteger)alarm_id {
//    if (_alarm_id == alarm_id) {
//        return;
//    }
//    
//    _alarm_id = alarm_id;
//    [self.imModel removeAll];
//    [self requestDeviceMsgList];
//}

//- (void)loadData {
//    int64_t delayInSeconds = 1;      // 延迟的时间
//    /*
//     *@parameter 1,时间参照，从此刻开始计时
//     *@parameter 2,延时多久，此处为秒级，还有纳秒等。10ull * NSEC_PER_MSEC
//     */
//    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
//    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//        // do something
//        [self addSomething];
//    });
//    
//    
//    
//}
//
//- (void)addSomething {
//    self.modelCnt += 10;
//    
//    //    CGSize oldSize = self.tableView.contentSize;
//    //    CGPoint oldOffset = self.tableView.contentOffset;
//    //    NSLog(@"oldSize = %@, oldOffset = %@", NSStringFromCGSize(oldSize), NSStringFromCGPoint(oldOffset));
//    [self.tableView reloadData];
//    
//    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:9 inSection:0];
//    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
//    [self.refreshControl endRefreshing];
//    
//    //    CGSize newSize = self.tableView.contentSize;
//    //    CGPoint newPoint = CGPointMake(0, oldOffset.y + newSize.height - oldSize.height);
//    //    NSLog(@"oldSize = %@, oldOffset = %@", NSStringFromCGSize(newSize), NSStringFromCGPoint(newPoint));
//    //    self.tableView.contentOffset = newPoint;
//}
//
//
//- (void)sendBtnTapped:(UIButton *)btn {
//    
//}

@end
